package com.syh.jn.scm.infrastructure.repository.impl.supplier.base.goods;

import cn.redscarf.commons.wrapper.Wrapper;
import com.syh.core.ddd.infrastructure.repository.AbstractAggregateRepository;
import com.syh.jn.scm.domain.supplier.entity.base.goods.Goods;
import com.syh.jn.scm.domain.supplier.repository.base.goods.GoodsRepository;
import com.syh.jn.scm.dto.supplier.base.goods.GoodsVo;
import com.syh.jn.scm.infrastructure.repository.model.base.goods.GoodsCategoryModel;
import com.syh.jn.scm.infrastructure.repository.model.base.goods.GoodsModel;
import com.syh.jn.scm.infrastructure.repository.utils.SQLAliasGenerateUtil;
import com.syh.jn.scm.infrastructure.wrapper.BaseResolve;
import com.syh.jn.scm.infrastructure.wrapper.ResolveToSQL;
import org.apache.ibatis.jdbc.SQL;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.HashMap;

@Repository
public class GoodsRepositoryImpl extends AbstractAggregateRepository<Goods, GoodsModel, Long> implements GoodsRepository {

  @Override
  public Long add(Goods goods) {
    Long id = super.add(goods);
    GoodsModel goodsModel = this.hibernateTemplate.get(GoodsModel.class, id);
    // 冗余分类的父类目录
    GoodsCategoryModel goodsCategory = this.hibernateTemplate.get(GoodsCategoryModel.class, goodsModel.getCategoryId());
    goodsModel.setCategoryCatalogCode(goodsCategory.getCatalogCode());
    goodsModel.setCategoryName(goodsCategory.getName());
    // 设置分类编码与商品编码
    goodsModel.setCode(goodsCategory.getCode() + String.format("%06d", id));

    if (goodsModel.getIsDefaultGoods().intValue() == 1) {
      goodsModel.setDefaultGoodsId(id);
      goodsModel.setConversionRate(BigDecimal.ONE);
    }
    return id;
  }

  @Override
  public void update(Goods goods) {
    GoodsCategoryModel goodsCategory = this.hibernateTemplate.get(GoodsCategoryModel.class, goods.getCategoryId());
    goods.setCode(goodsCategory.getCode() + String.format("%06d", goods.getId()));
    // 设置分类编码与商品编码
    goods.setCategoryCatalogCode(goodsCategory.getCatalogCode());

    if (goods.getIsDefaultGoods().intValue() == 1) {
      goods.setDefaultGoodsId(goods.getId());
      goods.setConversionRate(BigDecimal.ONE);
    }
    super.update(goods);
  }

  protected SQL getViewSql() {
    return new SQL() {{
      SELECT(
              SQLAliasGenerateUtil.aliasGenerate(GoodsModel.class, "goods", null),
              "brand.NAME AS goodsBrandName,manufacturer.NAME AS manufacturerName,origin.NAME AS originName"
      );
      FROM("T_BASE_GOODS goods");
      LEFT_OUTER_JOIN(
              "T_BASE_GOODS_BRAND brand on brand.ID = goods.GOODS_BRAND_ID",
              "T_BASE_MANUFACTURER manufacturer on manufacturer.ID = goods.MANUFACTURER_ID",
              "T_BASE_ORIGIN origin on origin.ID = goods.ORIGIN_ID"
      );
    }};
  }

  @Override
  protected BaseResolve getViewWrapperResolve(Wrapper wrapper) {
    HashMap<String, String> weMap = new HashMap<>();
    weMap.put("id", "goods.ID");
    weMap.put("name", "goods.NAME");
    weMap.put("code", "goods.CODE");
    weMap.put("categoryId", "goods.CATEGORY_ID");
    weMap.put("categoryCatalogCode", "goods.CATEGORY_CATALOG_CODE");
    weMap.put("status", "goods.STATUS");
    weMap.put("manufacturerId", "goods.MANUFACTURER_ID");
    weMap.put("originId", "goods.ORIGIN_ID");
    weMap.put("goodsBrandId", "goods.GOODS_BRAND_ID");
    weMap.put("businessEntityId", "goods.BUSINESS_ENTITY_ID");
    ResolveToSQL parse = new ResolveToSQL(wrapper, (propertyName) -> {
      return weMap.get(propertyName);
    });
    return parse;
  }

  protected Class getViewObject() {
    return GoodsVo.class;
  }

  /**
   * 根据参数字段查看是否已经被商品引用
   *
   * @param column
   * @param id
   * @return
   */
  @Override
  public boolean goodsExistsByColumn(String column, Long id) {
    StringBuffer hql = new StringBuffer("SELECT COUNT(*) FROM GoodsModel where ").append(column).append(" = ").append(id);
    this.getLogger().debug(hql.toString());
    Query query = buildQuery(hql);
    return ((Long) query.uniqueResult()).intValue() > 0;
  }
}
